package com.qos.fun;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.Messenger;

public class ActivityService {
    
    private Activity contx;
    private Messenger mService = null;
    boolean mIsBound = false;
    
    public ActivityService(Activity ctx) {
        contx = ctx;
    }
    
    public Messenger getMessenger() {
        return mService;
    }
    
    public boolean isBound() {
        return mIsBound;
    }
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // This is called when the connection with the service has been
            // established, giving us the service object we can use to
            // interact with the service.  We are communicating with our
            // service through an IDL interface, so get a client-side
            // representation of that from the raw service object.
            mService = new Messenger(service);

        }
        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            mService = null;

        }
    };
    
    void doBindService() {
        // Establish a connection with the service.  We use an explicit
        // class name because there is no reason to be able to let other
        // applications replace our component.
        contx.bindService(new Intent(contx, 
                ConnectManager.class), mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }
    
    void doUnbindService() {
        if (mIsBound) {
            
            // Detach our existing connection.
            contx.unbindService(mConnection);
            mIsBound = false;
        }
    }
}
